package com.minelx.datamicroscope.querylanguage.launch;

import com.alibaba.fastjson.JSONObject;
import com.minelx.datamicroscope.core.query.Query;
import com.minelx.datamicroscope.querylanguage.data.QueryBuilder;
import io.gitee.minelx.filesystem.File;
import io.gitee.minelx.filesystem.provider.FS;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;

import static io.gitee.minelx.filesystem.init.OpenPolicy.*;

public class OpenWithFileLauncher {
	public static void main(String[] args) throws IOException {
		if (args.length != 2) {
			throw new IllegalArgumentException("params.length should be 2: (file_path, only_explain)");
		}
		File source = FS.local().file(args[0].replace("\\", "/"), EXISTS);
		JSONObject queryJSON = QueryBuilder.sql(source.read(StandardCharsets.UTF_8));
		System.out.println("PARSED QUERY JSON: ");
		System.out.println("-------------------------------- START --------------------------------");
		System.out.println(queryJSON);
		System.out.println("--------------------------------- END ---------------------------------");

		// do execution if needed
		boolean onlyExplain = Boolean.parseBoolean(args[1]);
		if (!onlyExplain) {
			File destination = File.create(source.path().sibling(source.path().name() + "__"
					+ currentDateDescription() + ".csv"), CREATE);
			Query.localFSAndOnlineIndexWithPandasCalculationSupport(queryJSON)
					.queryTo(destination.path().uri());
		}
	}

	private static String currentDateDescription() {
		return new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss")
				.format(Date.from(Instant.now()));
	}
}
